import { useCallback, useState } from "react";
import { AESUtil } from "../utils/aes";

type AESResult = {
  encrypt: (plain: string) => string;
  decrypt: (cipher: string) => string;
  error: string | null;
};

export function useAES(): AESResult {
  const [error, setError] = useState<string | null>(null);

  const encrypt = useCallback((plain: string) => {
    setError(null);
    try {
      return AESUtil.encrypt(plain);
    } catch (e: any) {
      setError(e.message);
      return "";
    }
  }, []);

  const decrypt = useCallback((cipher: string) => {
    setError(null);
    try {
      return AESUtil.decrypt(cipher);
    } catch (e: any) {
      setError(e.message);
      return "";
    }
  }, []);

  return { encrypt, decrypt, error };
}
